package com.tanxin.bill.common.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.objectbox.reactive.DataSubscriptionList;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import me.yokeyword.fragmentation.SupportActivity;


/**
 * Created by TANXIN on 2017/6/27.
 */

public abstract class BaseActivity extends SupportActivity {
    private Unbinder unbinder;
    protected View contentView;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    protected DataSubscriptionList subscriptions = new DataSubscriptionList();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWindow();
        setBaseView();
        LogUtils.i(getClass().getName());
        unbinder = ButterKnife.bind(this);
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            getBundleExtras(extras);
        }
        initView(savedInstanceState);

        EventBus.getDefault().register(this);

    }

    public void setWindow(){}

    protected void setBaseView() {
        setContentView(contentView = LayoutInflater.from(this).inflate(bindLayout(), null));
    }

    protected abstract int bindLayout();


    /**
     * Bundle  传递数据
     *
     * @param extras Bundle
     */
    protected abstract void getBundleExtras(Bundle extras);



    protected abstract void initView(Bundle savedInstanceState);

    /**
     * EventBus接收消息
     *
     * @param event 获取事件总线信息
     */
    protected abstract void onEventComing(BaseEvent event);

    /**
     * EventBus接收消息
     *
     * @param event 消息接收
     */
    @Subscribe
    public void onEventMainThread(BaseEvent event) {
        if (null != event) {
            onEventComing(event);
        }

    }

    public void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public Context getContext(){
        return this;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解绑ButterKnife
        unbinder.unbind();
        subscriptions.cancel();
        EventBus.getDefault().unregister(this);
        dispose();
    }

    private void dispose() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    public void addDisposable(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }


}
